home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 21 / AACD 21.iso / AACD / Utilities / Ghostscript / src / isave.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-01-01  |  33.2 KB  |  1,121 lines

  1. /* Copyright (C) 1993, 2000 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of AFPL Ghostscript.
  4.   
  5.   AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author or
  6.   distributor accepts any responsibility for the consequences of using it, or
  7.   for whether it serves any particular purpose or works at all, unless he or
  8.   she says so in writing.  Refer to the Aladdin Free Public License (the
  9.   "License") for full details.
  10.   
  11.   Every copy of AFPL Ghostscript must include a copy of the License, normally
  12.   in a plain ASCII text file named PUBLIC.  The License grants you the right
  13.   to copy, modify and redistribute AFPL Ghostscript, but only under certain
  14.   conditions described in the License.  Among other things, the License
  15.   requires that the copyright notice and this notice be preserved on all
  16.   copies.
  17. */
  18.  
  19. /*$Id: isave.c,v 1.3 2000/09/19 19:00:46 lpd Exp $ */
  20. /* Save/restore manager for Ghostscript interpreter */
  21. #include "ghost.h"
  22. #include "memory_.h"
  23. #include "errors.h"
  24. #include "gsexit.h"
  25. #include "gsstruct.h"
  26. #include "stream.h"        /* for linking for forgetsave */
  27. #include "iastate.h"
  28. #include "inamedef.h"
  29. #include "iname.h"
  30. #include "ipacked.h"
  31. #include "isave.h"
  32. #include "isstate.h"
  33. #include "store.h"        /* for ref_assign */
  34. #include "ivmspace.h"
  35. #include "gsutil.h"        /* gs_next_ids prototype */
  36.  
  37. /* Imported save/restore routines */
  38. extern void font_restore(P1(const alloc_save_t *));
  39.  
  40. /* Structure descriptor */
  41. private_st_alloc_save();
  42.  
  43. /* Define the maximum amount of data we are willing to scan repeatedly -- */
  44. /* see below for details. */
  45. private const long max_repeated_scan = 100000;
  46.  
  47. /*
  48.  * The logic for saving and restoring the state is complex.
  49.  * Both the changes to individual objects, and the overall state
  50.  * of the memory manager, must be saved and restored.
  51.  */
  52.  
  53. /*
  54.  * To save the state of the memory manager:
  55.  *      Save the state of the current chunk in which we are allocating.
  56.  *      Shrink the current chunk to its inner unallocated region.
  57.  *      Save and reset the free block chains.
  58.  * By doing this, we guarantee that no object older than the save
  59.  * can be freed.
  60.  *
  61.  * To restore the state of the memory manager:
  62.  *      Free all chunks newer than the save, and the descriptor for
  63.  *        the inner chunk created by the save.
  64.  *      Make current the chunk that was current at the time of the save.
  65.  *      Restore the state of the current chunk.
  66.  *
  67.  * In addition to save ("start transaction") and restore ("abort transaction"),
  68.  * we support forgetting a save ("commit transation").  To forget a save:
  69.  *      Reassign to the next outer save all chunks newer than the save.
  70.  *      Free the descriptor for the inner chunk, updating its outer chunk
  71.  *        to reflect additional allocations in the inner chunk.
  72.  *      Concatenate the free block chains with those of the outer save.
  73.  */
  74.  
  75. /*
  76.  * For saving changes to individual objects, we add an "attribute" bit
  77.  * (l_new) that logically belongs to the slot where the ref is stored,
  78.  * not to the ref itself.  The bit means "the contents of this slot
  79.  * have been changed, or the slot was allocated, since the last save."
  80.  * To keep track of changes since the save, we associate a chain of
  81.  * <slot, old_contents> pairs that remembers the old contents of slots.
  82.  *
  83.  * When creating an object, if the save level is non-zero:
  84.  *      Set l_new in all slots.
  85.  *
  86.  * When storing into a slot, if the save level is non-zero:
  87.  *      If l_new isn't set, save the address and contents of the slot
  88.  *        on the current contents chain.
  89.  *      Set l_new after storing the new value.
  90.  *
  91.  * To do a save:
  92.  *      If the save level is non-zero:
  93.  *              Reset l_new in all slots on the contents chain, and in all
  94.  *                objects created since the previous save.
  95.  *      Push the head of the contents chain, and reset the chain to empty.
  96.  *
  97.  * To do a restore:
  98.  *      Check all the stacks to make sure they don't contain references
  99.  *        to objects created since the save.
  100.  *      Restore all the slots on the contents chain.
  101.  *      Pop the contents chain head.
  102.  *      If the save level is now non-zero:
  103.  *              Scan the newly restored contents chain, and set l_new in all
  104.  *                the slots it references.
  105.  *              Scan all objects created since the previous save, and set
  106.  *                l_new in all the slots of each object.
  107.  *
  108.  * To forget a save:
  109.  *      If the save level is greater than 1:
  110.  *              Set l_new as for a restore, per the next outer save.
  111.  *              Concatenate the next outer contents chain to the end of
  112.  *                the current one.
  113.  *      If the save level is 1:
  114.  *              Reset l_new as for a save.
  115.  *              Free the contents chain.
  116.  */
  117.  
  118. /*
  119.  * A consequence of the foregoing algorithms is that the cost of a save is
  120.  * proportional to the total amount of data allocated since the previous
  121.  * save.  If a PostScript program reads in a large amount of setup code and
  122.  * then uses save/restore heavily, each save/restore will be expensive.  To
  123.  * mitigate this, we check to see how much data we have scanned at this save
  124.  * level: if it is large, we do a second, invisible save.  This greatly
  125.  * reduces the cost of inner saves, at the expense of possibly saving some
  126.  * changes twice that otherwise would only have to be saved once.
  127.  */
  128.  
  129. /*
  130.  * The presence of global and local VM complicates the situation further.
  131.  * There is a separate save chain and contents chain for each VM space.
  132.  * When multiple contexts are fully implemented, save and restore will have
  133.  * the following effects, according to the privacy status of the current
  134.  * context's global and local VM:
  135.  *      Private global, private local:
  136.  *              The outermost save saves both global and local VM;
  137.  *                otherwise, save only saves local VM.
  138.  *      Shared global, private local:
  139.  *              Save only saves local VM.
  140.  *      Shared global, shared local:
  141.  *              Save only saves local VM, and suspends all other contexts
  142.  *                sharing the same local VM until the matching restore.
  143.  * Since we do not currently implement multiple contexts, only the first
  144.  * case is relevant.
  145.  *
  146.  * Note that when saving the contents of a slot, the choice of chain
  147.  * is determined by the VM space in which the slot is allocated,
  148.  * not by the current allocation mode.
  149.  */
  150.  
  151. /* Tracing printout */
  152. private void
  153. print_save(const char *str, uint spacen, const alloc_save_t *sav)
  154. {
  155.   if_debug5('u', "[u]%s space %u 0x%lx: cdata = 0x%lx, id = %lu\n",\
  156.         str, spacen, (ulong)sav, (ulong)sav->client_data, (ulong)sav->id);
  157. }
  158.  
  159. /*
  160.  * Structure for saved change chain for save/restore.  Because of the
  161.  * garbage collector, we need to distinguish the cases where the change
  162.  * is in a static object, a dynamic ref, or a dynamic struct.
  163.  */
  164. typedef struct alloc_change_s alloc_change_t;
  165. struct alloc_change_s {
  166.     alloc_change_t *next;
  167.     ref_packed *where;
  168.     ref contents;
  169. #define AC_OFFSET_STATIC (-2)    /* static object */
  170. #define AC_OFFSET_REF (-1)    /* dynamic ref */
  171.     short offset;        /* if >= 0, offset within struct */
  172. };
  173.  
  174. private 
  175. CLEAR_MARKS_PROC(change_clear_marks)
  176. {
  177.     alloc_change_t *const ptr = (alloc_change_t *)vptr;
  178.  
  179.     if (r_is_packed(&ptr->contents))
  180.     r_clear_pmark((ref_packed *) & ptr->contents);
  181.     else
  182.     r_clear_attrs(&ptr->contents, l_mark);
  183. }
  184. private 
  185. ENUM_PTRS_WITH(change_enum_ptrs, alloc_change_t *ptr) return 0;
  186. ENUM_PTR(0, alloc_change_t, next);
  187. case 1:
  188.     if (ptr->offset >= 0)
  189.     ENUM_RETURN((byte *) ptr->where - ptr->offset);
  190.     else
  191.     ENUM_RETURN_REF(ptr->where);
  192. case 2:
  193.     ENUM_RETURN_REF(&ptr->contents);
  194. ENUM_PTRS_END
  195. private RELOC_PTRS_WITH(change_reloc_ptrs, alloc_change_t *ptr)
  196. {
  197.     RELOC_VAR(ptr->next);
  198.     switch (ptr->offset) {
  199.     case AC_OFFSET_STATIC:
  200.         break;
  201.     case AC_OFFSET_REF:
  202.         RELOC_REF_PTR_VAR(ptr->where);
  203.         break;
  204.     default:
  205.         {
  206.         byte *obj = (byte *) ptr->where - ptr->offset;
  207.  
  208.         RELOC_VAR(obj);
  209.         ptr->where = (ref_packed *) (obj + ptr->offset);
  210.         }
  211.         break;
  212.     }
  213.     if (r_is_packed(&ptr->contents))
  214.     r_clear_pmark((ref_packed *) & ptr->contents);
  215.     else {
  216.     RELOC_REF_VAR(ptr->contents);
  217.     r_clear_attrs(&ptr->contents, l_mark);
  218.     }
  219. }
  220. RELOC_PTRS_END
  221. gs_private_st_complex_only(st_alloc_change, alloc_change_t, "alloc_change",
  222.         change_clear_marks, change_enum_ptrs, change_reloc_ptrs, 0);
  223.  
  224. /* Debugging printout */
  225. #ifdef DEBUG
  226. private void
  227. alloc_save_print(alloc_change_t * cp, bool print_current)
  228. {
  229.     dprintf2(" 0x%lx: 0x%lx: ", (ulong) cp, (ulong) cp->where);
  230.     if (r_is_packed(&cp->contents)) {
  231.     if (print_current)
  232.         dprintf2("saved=%x cur=%x\n", *(ref_packed *) & cp->contents,
  233.              *cp->where);
  234.     else
  235.         dprintf1("%x\n", *(ref_packed *) & cp->contents);
  236.     } else {
  237.     if (print_current)
  238.         dprintf6("saved=%x %x %lx cur=%x %x %lx\n",
  239.              r_type_attrs(&cp->contents), r_size(&cp->contents),
  240.              (ulong) cp->contents.value.intval,
  241.              r_type_attrs((ref *) cp->where),
  242.              r_size((ref *) cp->where),
  243.              (ulong) ((ref *) cp->where)->value.intval);
  244.     else
  245.         dprintf3("%x %x %lx\n",
  246.              r_type_attrs(&cp->contents), r_size(&cp->contents),
  247.              (ulong) cp->contents.value.intval);
  248.     }
  249. }
  250. #endif
  251.  
  252. /* Forward references */
  253. private void restore_resources(P2(alloc_save_t *, gs_ref_memory_t *));
  254. private void restore_free(P1(gs_ref_memory_t *));
  255. private long save_set_new(P2(gs_ref_memory_t *, bool));
  256. private void save_set_new_changes(P2(gs_ref_memory_t *, bool));
  257.  
  258. /* Initialize the save/restore machinery. */
  259. void
  260. alloc_save_init(gs_dual_memory_t * dmem)
  261. {
  262.     alloc_set_not_in_save(dmem);
  263. }
  264.  
  265. /* Record that we are in a save. */
  266. private void
  267. alloc_set_masks(gs_dual_memory_t *dmem, uint new_mask, uint test_mask)
  268. {
  269.     int i;
  270.     gs_ref_memory_t *mem;
  271.  
  272.     dmem->new_mask = new_mask;
  273.     dmem->test_mask = test_mask;
  274.     for (i = 0; i < countof(dmem->spaces.memories.indexed); ++i)
  275.     if ((mem = dmem->spaces.memories.indexed[i]) != 0) {
  276.         mem->new_mask = new_mask, mem->test_mask = test_mask;
  277.         if (mem->stable_memory != (gs_memory_t *)mem) {
  278.         mem = (gs_ref_memory_t *)mem->stable_memory;
  279.         mem->new_mask = new_mask, mem->test_mask = test_mask;
  280.         }
  281.     }
  282. }
  283. void
  284. alloc_set_in_save(gs_dual_memory_t *dmem)
  285. {
  286.     alloc_set_masks(dmem, l_new, l_new);
  287. }
  288.  
  289. /* Record that we are not in a save. */
  290. void
  291. alloc_set_not_in_save(gs_dual_memory_t *dmem)
  292. {
  293.     alloc_set_masks(dmem, 0, ~0);
  294. }
  295.  
  296. /* Save the state. */
  297. private alloc_save_t *alloc_save_space(P3(gs_ref_memory_t *mem,
  298.                       gs_dual_memory_t *dmem,
  299.                       ulong sid));
  300. private void
  301. alloc_free_save(gs_ref_memory_t *mem, alloc_save_t *save, const char *scn,
  302.         const char *icn)
  303. {
  304.     chunk_t *inner = mem->pcc;
  305.  
  306.     gs_free_object((gs_memory_t *)mem, save, scn);
  307.     gs_free_object(mem->parent, inner, icn);
  308. }
  309. ulong
  310. alloc_save_state(gs_dual_memory_t * dmem, void *cdata)
  311. {
  312.     gs_ref_memory_t *lmem = dmem->space_local;
  313.     gs_ref_memory_t *gmem = dmem->space_global;
  314.     ulong sid = gs_next_ids(2);
  315.     bool global =
  316.     lmem->save_level == 0 && gmem != lmem &&
  317.     gmem->num_contexts == 1;
  318.     alloc_save_t *gsave =
  319.     (global ? alloc_save_space(gmem, dmem, sid + 1) : (alloc_save_t *) 0);
  320.     alloc_save_t *lsave = alloc_save_space(lmem, dmem, sid);
  321.  
  322.     if (lsave == 0 || (global &&gsave == 0)) {
  323.     if (lsave != 0)
  324.         alloc_free_save(lmem, lsave, "alloc_save_state(local save)",
  325.                 "alloc_save_state(local inner)");
  326.     if (gsave != 0)
  327.         alloc_free_save(gmem, gsave, "alloc_save_state(global save)",
  328.                 "alloc_save_state(global inner)");
  329.     return 0;
  330.     }
  331.     if (gsave != 0) {
  332.     gsave->client_data = 0;
  333.     print_save("save", gmem->space, gsave);
  334.     /* Restore names when we do the local restore. */
  335.     lsave->restore_names = gsave->restore_names;
  336.     gsave->restore_names = false;
  337.     }
  338.     lsave->id = sid;
  339.     lsave->client_data = cdata;
  340.     print_save("save", lmem->space, lsave);
  341.     /* Reset the l_new attribute in all slots.  The only slots that */
  342.     /* can have the attribute set are the ones on the changes chain, */
  343.     /* and ones in objects allocated since the last save. */
  344.     if (lmem->save_level > 1) {
  345.     long scanned = save_set_new(&lsave->state, false);
  346.  
  347.     if ((lsave->state.total_scanned += scanned) > max_repeated_scan) {
  348.         /* Do a second, invisible save. */
  349.         alloc_save_t *rsave;
  350.  
  351.         rsave = alloc_save_space(lmem, dmem, 0L);
  352.         if (rsave != 0) {
  353.         rsave->client_data = cdata;
  354.         rsave->id = lsave->id;
  355.         print_save("save", lmem->space, rsave);
  356.         lsave->id = 0;    /* mark as invisible */
  357.         rsave->state.save_level--; /* ditto */
  358.         lsave->client_data = 0;
  359.         /* Inherit the allocated space count -- */
  360.         /* we need this for triggering a GC. */
  361.         rsave->state.inherited =
  362.             lsave->state.allocated + lsave->state.inherited;
  363.         lmem->inherited = rsave->state.inherited;
  364.         print_save("save", lmem->space, lsave);
  365.         }
  366.     }
  367.     }
  368.     alloc_set_in_save(dmem);
  369.     return sid;
  370. }
  371. /* Save the state of one space (global or local). */
  372. private alloc_save_t *
  373. alloc_save_space(gs_ref_memory_t * mem, gs_dual_memory_t * dmem, ulong sid)
  374. {
  375.     gs_ref_memory_t save_mem;
  376.     alloc_save_t *save;
  377.     chunk_t *inner = 0;
  378.  
  379.     if (mem->cc.ctop - mem->cc.cbot > sizeof(chunk_head_t)) {
  380.     inner = gs_raw_alloc_struct_immovable(mem->parent, &st_chunk,
  381.                           "alloc_save_space(inner)");
  382.     if (inner == 0)
  383.         return 0;
  384.     }
  385.     save_mem = *mem;
  386.     alloc_close_chunk(mem);
  387.     gs_memory_status((gs_memory_t *) mem, &mem->previous_status);
  388.     ialloc_reset(mem);
  389.     mem->cc.cnext = mem->cc.cprev = 0;
  390.     if (inner != 0) {        /* Create an inner chunk to cover only the unallocated part. */
  391.     alloc_init_chunk(&mem->cc, mem->cc.cbot, mem->cc.ctop,
  392.              true, mem->pcc);
  393.     *inner = mem->cc;
  394.     mem->pcc = inner;
  395.     mem->cfirst = mem->clast = inner;
  396.     } else {            /* Not enough room to create an inner chunk. */
  397.     mem->pcc = 0;
  398.     mem->cfirst = mem->clast = 0;
  399.     mem->cc.cbot = mem->cc.ctop = 0;
  400.     }
  401.     save = gs_alloc_struct((gs_memory_t *) mem, alloc_save_t,
  402.                &st_alloc_save, "alloc_save_space(save)");
  403. #ifdef DEBUG
  404.     if (inner != 0) {
  405.     if_debug4('u',
  406.           "[u]save space %u at 0x%lx: cbot=0x%lx ctop=0x%lx\n",
  407.           mem->space, (ulong) save,
  408.           (ulong) inner->cbot, (ulong) inner->ctop);
  409.     } else {
  410.     if_debug2('u',
  411.           "[u]save space %u at 0x%lx (no inner)\n",
  412.           mem->space, (ulong) save);
  413.     }
  414. #endif
  415.     if (save == 0) {
  416.     gs_free_object(mem->parent, inner, "alloc_save_space(inner)");
  417.     *mem = save_mem;
  418.     return 0;
  419.     }
  420.     save->state = save_mem;
  421.     save->spaces = dmem->spaces;
  422.     save->restore_names = (name_memory() == (gs_memory_t *) mem);
  423.     save->is_current = (dmem->current == mem);
  424.     save->id = sid;
  425.     mem->saved = save;
  426.     if_debug2('u', "[u%u]file_save 0x%lx\n",
  427.           mem->space, (ulong) mem->streams);
  428.     mem->streams = 0;
  429.     mem->total_scanned = 0;
  430.     if (sid)
  431.     mem->save_level++;
  432.     return save;
  433. }
  434.  
  435. /* Record a state change that must be undone for restore, */
  436. /* and mark it as having been saved. */
  437. int
  438. alloc_save_change_in(gs_ref_memory_t *mem, const ref * pcont,
  439.           ref_packed * where, client_name_t cname)
  440. {
  441.     register alloc_change_t *cp;
  442.  
  443.     if (mem->new_mask == 0)
  444.     return 0;        /* no saving */
  445.     cp = gs_alloc_struct((gs_memory_t *)mem, alloc_change_t,
  446.              &st_alloc_change, "alloc_save_change");
  447.     if (cp == 0)
  448.     return -1;
  449.     cp->next = mem->changes;
  450.     cp->where = where;
  451.     if (pcont == NULL)
  452.     cp->offset = AC_OFFSET_STATIC;
  453.     else if (r_is_array(pcont) || r_has_type(pcont, t_dictionary))
  454.     cp->offset = AC_OFFSET_REF;
  455.     else if (r_is_struct(pcont))
  456.     cp->offset = (byte *) where - (byte *) pcont->value.pstruct;
  457.     else {
  458.     lprintf3("Bad type %u for save!  pcont = 0x%lx, where = 0x%lx\n",
  459.          r_type(pcont), (ulong) pcont, (ulong) where);
  460.     gs_abort();
  461.     }
  462.     if (r_is_packed(where))
  463.     *(ref_packed *)&cp->contents = *where;
  464.     else {
  465.     ref_assign_inline(&cp->contents, (ref *) where);
  466.     r_set_attrs((ref *) where, l_new);
  467.     }
  468.     mem->changes = cp;
  469. #ifdef DEBUG
  470.     if (gs_debug_c('U')) {
  471.     dlprintf1("[U]save(%s)", client_name_string(cname));
  472.     alloc_save_print(cp, false);
  473.     }
  474. #endif
  475.     return 0;
  476. }
  477. int
  478. alloc_save_change(gs_dual_memory_t * dmem, const ref * pcont,
  479.           ref_packed * where, client_name_t cname)
  480. {
  481.     gs_ref_memory_t *mem =
  482.     (pcont == NULL ? dmem->space_local :
  483.      dmem->spaces_indexed[r_space(pcont) >> r_space_shift]);
  484.  
  485.     return alloc_save_change_in(mem, pcont, where, cname);
  486. }
  487.  
  488. /* Return (the id of) the innermost externally visible save object, */
  489. /* i.e., the innermost save with a non-zero ID. */
  490. ulong
  491. alloc_save_current_id(const gs_dual_memory_t * dmem)
  492. {
  493.     const alloc_save_t *save = dmem->space_local->saved;
  494.  
  495.     while (save != 0 && save->id == 0)
  496.     save = save->state.saved;
  497.     return save->id;
  498. }
  499. alloc_save_t *
  500. alloc_save_current(const gs_dual_memory_t * dmem)
  501. {
  502.     return alloc_find_save(dmem, alloc_save_current_id(dmem));
  503. }
  504.  
  505. /* Test whether a reference would be invalidated by a restore. */
  506. bool
  507. alloc_is_since_save(const void *vptr, const alloc_save_t * save)
  508. {
  509.     /* A reference postdates a save iff it is in a chunk allocated */
  510.     /* since the save (including the carried-over inner chunk). */
  511.  
  512.     const char *const ptr = (const char *)vptr;
  513.     register const gs_ref_memory_t *mem = save->space_local;
  514.  
  515.     if_debug2('U', "[U]is_since_save 0x%lx, 0x%lx:\n",
  516.           (ulong) ptr, (ulong) save);
  517.     if (mem->saved == 0) {    /* This is a special case, the final 'restore' from */
  518.     /* alloc_restore_all. */
  519.     return true;
  520.     }
  521.     /* Check against chunks allocated since the save. */
  522.     /* (There may have been intermediate saves as well.) */
  523.     for (;; mem = &mem->saved->state) {
  524.     const chunk_t *cp;
  525.  
  526.     if_debug1('U', "[U]checking mem=0x%lx\n", (ulong) mem);
  527.     for (cp = mem->cfirst; cp != 0; cp = cp->cnext) {
  528.         if (ptr_is_within_chunk(ptr, cp)) {
  529.         if_debug3('U', "[U+]in new chunk 0x%lx: 0x%lx, 0x%lx\n",
  530.               (ulong) cp,
  531.               (ulong) cp->cbase, (ulong) cp->cend);
  532.         return true;
  533.         }
  534.         if_debug1('U', "[U-]not in 0x%lx\n", (ulong) cp);
  535.     }
  536.     if (mem->saved == save) {    /* We've checked all the more recent saves, */
  537.         /* must be OK. */
  538.         break;
  539.     }
  540.     }
  541.  
  542.     /*
  543.      * If we're about to do a global restore (save level = 1),
  544.      * and there is only one context using this global VM
  545.      * (the normal case, in which global VM is saved by the
  546.      * outermost save), we also have to check the global save.
  547.      * Global saves can't be nested, which makes things easy.
  548.      */
  549.     if (mem->save_level == 1 &&
  550.     (mem = save->space_global) != save->space_local &&
  551.     save->space_global->num_contexts == 1
  552.     ) {
  553.     const chunk_t *cp;
  554.  
  555.     if_debug1('U', "[U]checking global mem=0x%lx\n", (ulong) mem);
  556.     for (cp = mem->cfirst; cp != 0; cp = cp->cnext)
  557.         if (ptr_is_within_chunk(ptr, cp)) {
  558.         if_debug3('U', "[U+]  new chunk 0x%lx: 0x%lx, 0x%lx\n",
  559.               (ulong) cp, (ulong) cp->cbase, (ulong) cp->cend);
  560.         return true;
  561.         }
  562.     }
  563.     return false;
  564.  
  565. #undef ptr
  566. }
  567.  
  568. /* Test whether a name would be invalidated by a restore. */
  569. bool
  570. alloc_name_is_since_save(const ref * pnref, const alloc_save_t * save)
  571. {
  572.     const name_string_t *pnstr;
  573.  
  574.     if (!save->restore_names)
  575.     return false;
  576.     pnstr = names_string_inline(the_gs_name_table, pnref);
  577.     if (pnstr->foreign_string)
  578.     return false;
  579.     return alloc_is_since_save(pnstr->string_bytes, save);
  580. }
  581. bool
  582. alloc_name_index_is_since_save(uint nidx, const alloc_save_t * save)
  583. {
  584.     ref nref;
  585.  
  586.     nref.value.pname = name_index_ptr(nidx);
  587.     return alloc_name_is_since_save(&nref, save);
  588. }
  589.  
  590. /* Check whether any names have been created since a given save */
  591. /* that might be released by the restore. */
  592. bool
  593. alloc_any_names_since_save(const alloc_save_t * save)
  594. {
  595.     return save->restore_names;
  596. }
  597.  
  598. /* Get the saved state with a given ID. */
  599. alloc_save_t *
  600. alloc_find_save(const gs_dual_memory_t * dmem, ulong sid)
  601. {
  602.     alloc_save_t *sprev = dmem->space_local->saved;
  603.  
  604.     if (sid == 0)
  605.     return 0;        /* invalid id */
  606.     while (sprev != 0) {
  607.     if (sprev->id == sid)
  608.         return sprev;
  609.     sprev = sprev->state.saved;
  610.     }
  611.     return 0;
  612. }
  613.  
  614. /* Get the client data from a saved state. */
  615. void *
  616. alloc_save_client_data(const alloc_save_t * save)
  617. {
  618.     return save->client_data;
  619. }
  620.  
  621. /*
  622.  * Do one step of restoring the state.  The client is responsible for
  623.  * calling alloc_find_save to get the save object, and for ensuring that
  624.  * there are no surviving pointers for which alloc_is_since_save is true.
  625.  * Return true if the argument was the innermost save, in which case
  626.  * this is the last (or only) step.
  627.  * Note that "one step" may involve multiple internal steps,
  628.  * if this is the outermost restore (which requires restoring both local
  629.  * and global VM) or if we created extra save levels to reduce scanning.
  630.  */
  631. private void restore_finalize(P1(gs_ref_memory_t *));
  632. private void restore_space(P2(gs_ref_memory_t *, gs_dual_memory_t *));
  633.  
  634. bool
  635. alloc_restore_step_in(gs_dual_memory_t *dmem, alloc_save_t * save)
  636. {
  637.     /* Get save->space_* now, because the save object will be freed. */
  638.     gs_ref_memory_t *lmem = save->space_local;
  639.     gs_ref_memory_t *gmem = save->space_global;
  640.     gs_ref_memory_t *mem = lmem;
  641.     alloc_save_t *sprev;
  642.  
  643.     /* Finalize all objects before releasing resources or undoing changes. */
  644.     do {
  645.     ulong sid;
  646.  
  647.     sprev = mem->saved;
  648.     sid = sprev->id;
  649.     restore_finalize(mem);    /* finalize objects */
  650.     mem = &sprev->state;
  651.     if (sid != 0)
  652.         break;
  653.     }
  654.     while (sprev != save);
  655.     if (mem->save_level == 0) {
  656.     /* This is the outermost save, which might also */
  657.     /* need to restore global VM. */
  658.     mem = gmem;
  659.     if (mem != lmem && mem->saved != 0)
  660.         restore_finalize(mem);
  661.     }
  662.  
  663.     /* Do one (externally visible) step of restoring the state. */
  664.     mem = lmem;
  665.     do {
  666.     ulong sid;
  667.  
  668.     sprev = mem->saved;
  669.     sid = sprev->id;
  670.     restore_resources(sprev, mem);    /* release other resources */
  671.     restore_space(mem, dmem);    /* release memory */
  672.     if (sid != 0)
  673.         break;
  674.     }
  675.     while (sprev != save);
  676.  
  677.     if (mem->save_level == 0) {
  678.     /* This is the outermost save, which might also */
  679.     /* need to restore global VM. */
  680.     mem = gmem;
  681.     if (mem != lmem && mem->saved != 0) {
  682.         restore_resources(mem->saved, mem);
  683.         restore_space(mem, dmem);
  684.     }
  685.     alloc_set_not_in_save(dmem);
  686.     } else {            /* Set the l_new attribute in all slots that are now new. */
  687.     save_set_new(mem, true);
  688.     }
  689.  
  690.     return sprev == save;
  691. }
  692. /* Restore the memory of one space, by undoing changes and freeing */
  693. /* memory allocated since the save. */
  694. private void
  695. restore_space(gs_ref_memory_t * mem, gs_dual_memory_t *dmem)
  696. {
  697.     alloc_save_t *save = mem->saved;
  698.     alloc_save_t saved;
  699.  
  700.     print_save("restore", mem->space, save);
  701.  
  702.     /* Undo changes since the save. */
  703.     {
  704.     register alloc_change_t *cp = mem->changes;
  705.  
  706.     while (cp) {
  707. #ifdef DEBUG
  708.         if (gs_debug_c('U')) {
  709.         dlputs("[U]restore");
  710.         alloc_save_print(cp, true);
  711.         }
  712. #endif
  713.         if (r_is_packed(&cp->contents))
  714.         *cp->where = *(ref_packed *) & cp->contents;
  715.         else
  716.         ref_assign_inline((ref *) cp->where, &cp->contents);
  717.         cp = cp->next;
  718.     }
  719.     }
  720.  
  721.     /* Free memory allocated since the save. */
  722.     /* Note that this frees all chunks except the inner one */
  723.     /* belonging to this level. */
  724.     saved = *save;
  725.     restore_free(mem);
  726.  
  727.     /* Restore the allocator state. */
  728.     {
  729.     int num_contexts = mem->num_contexts;    /* don't restore */
  730.  
  731.     *mem = saved.state;
  732.     mem->num_contexts = num_contexts;
  733.     }
  734.     alloc_open_chunk(mem);
  735.  
  736.     /* Make the allocator current if it was current before the save. */
  737.     if (saved.is_current) {
  738.     dmem->current = mem;
  739.     dmem->current_space = mem->space;
  740.     }
  741. }
  742.  
  743. /* Restore to the initial state, releasing all resources. */
  744. /* The allocator is no longer usable after calling this routine! */
  745. void
  746. alloc_restore_all(gs_dual_memory_t * dmem)
  747. {
  748.     /*
  749.      * Save the memory pointers, since freeing space_local will also
  750.      * free dmem itself.
  751.      */
  752.     gs_ref_memory_t *lmem = dmem->space_local;
  753.     gs_ref_memory_t *gmem = dmem->space_global;
  754.     gs_ref_memory_t *smem = dmem->space_system;
  755.     gs_ref_memory_t *mem;
  756.  
  757.     /* Restore to a state outside any saves. */
  758.     while (lmem->save_level != 0)
  759.     discard(alloc_restore_step_in(dmem, lmem->saved));
  760.  
  761.     /* Finalize memory. */
  762.     restore_finalize(lmem);
  763.     if ((mem = (gs_ref_memory_t *)lmem->stable_memory) != lmem)
  764.     restore_finalize(mem);
  765.     if (gmem != lmem && gmem->num_contexts == 1) {
  766.     restore_finalize(gmem);
  767.     if ((mem = (gs_ref_memory_t *)gmem->stable_memory) != gmem)
  768.         restore_finalize(mem);
  769.     }
  770.     restore_finalize(smem);
  771.  
  772.     /* Release resources other than memory, using fake */
  773.     /* save and memory objects. */
  774.     {
  775.     alloc_save_t empty_save;
  776.  
  777.     empty_save.spaces = dmem->spaces;
  778.     empty_save.restore_names = false;    /* don't bother to release */
  779.     restore_resources(&empty_save, NULL);
  780.     }
  781.  
  782.     /* Finally, release memory. */
  783.     restore_free(lmem);
  784.     if ((mem = (gs_ref_memory_t *)lmem->stable_memory) != lmem)
  785.     restore_free(mem);
  786.     if (gmem != lmem) {
  787.     if (!--(gmem->num_contexts)) {
  788.         restore_free(gmem);
  789.         if ((mem = (gs_ref_memory_t *)gmem->stable_memory) != gmem)
  790.         restore_free(mem);
  791.     }
  792.     }
  793.     restore_free(smem);
  794.  
  795. }
  796.  
  797. /*
  798.  * Finalize objects that will be freed by a restore.
  799.  * Note that we must temporarily disable the freeing operations
  800.  * of the allocator while doing this.
  801.  */
  802. private void
  803. restore_finalize(gs_ref_memory_t * mem)
  804. {
  805.     chunk_t *cp;
  806.  
  807.     alloc_close_chunk(mem);
  808.     gs_enable_free((gs_memory_t *) mem, false);
  809.     for (cp = mem->clast; cp != 0; cp = cp->cprev) {
  810.     SCAN_CHUNK_OBJECTS(cp)
  811.         DO_ALL
  812.         struct_proc_finalize((*finalize)) =
  813.         pre->o_type->finalize;
  814.     if (finalize != 0) {
  815.         if_debug2('u', "[u]restore finalizing %s 0x%lx\n",
  816.               struct_type_name_string(pre->o_type),
  817.               (ulong) (pre + 1));
  818.         (*finalize) (pre + 1);
  819.     }
  820.     END_OBJECTS_SCAN
  821.     }
  822.     gs_enable_free((gs_memory_t *) mem, true);
  823. }
  824.  
  825. /* Release resources for a restore */
  826. private void
  827. restore_resources(alloc_save_t * sprev, gs_ref_memory_t * mem)
  828. {
  829. #ifdef DEBUG
  830.     if (mem) {
  831.     /* Note restoring of the file list. */
  832.     if_debug4('u', "[u%u]file_restore 0x%lx => 0x%lx for 0x%lx\n",
  833.           mem->space, (ulong)mem->streams,
  834.           (ulong)sprev->state.streams, (ulong) sprev);
  835.     }
  836. #endif
  837.  
  838.     /* Remove entries from font and character caches. */
  839.     font_restore(sprev);
  840.  
  841.     /* Adjust the name table. */
  842.     if (sprev->restore_names)
  843.     names_restore(the_gs_name_table, sprev);
  844. }
  845.  
  846. /* Release memory for a restore. */
  847. private void
  848. restore_free(gs_ref_memory_t * mem)
  849. {
  850.     /* Free chunks allocated since the save. */
  851.     gs_free_all((gs_memory_t *) mem);
  852. }
  853.  
  854. /* Forget a save, by merging this level with the next outer one. */
  855. private void file_forget_save(P1(gs_ref_memory_t *));
  856. private void combine_space(P1(gs_ref_memory_t *));
  857. private void forget_changes(P1(gs_ref_memory_t *));
  858. void
  859. alloc_forget_save_in(gs_dual_memory_t *dmem, alloc_save_t * save)
  860. {
  861.     gs_ref_memory_t *mem = save->space_local;
  862.     alloc_save_t *sprev;
  863.  
  864.     print_save("forget_save", mem->space, save);
  865.  
  866.     /* Iteratively combine the current level with the previous one. */
  867.     do {
  868.     sprev = mem->saved;
  869.     if (sprev->id != 0)
  870.         mem->save_level--;
  871.     if (mem->save_level != 0) {
  872.         alloc_change_t *chp = mem->changes;
  873.  
  874.         save_set_new(&sprev->state, true);
  875.         /* Concatenate the changes chains. */
  876.         if (chp == 0)
  877.         mem->changes = sprev->state.changes;
  878.         else {
  879.         while (chp->next != 0)
  880.             chp = chp->next;
  881.         chp->next = sprev->state.changes;
  882.         }
  883.         file_forget_save(mem);
  884.         combine_space(mem);    /* combine memory */
  885.     } else {
  886.         forget_changes(mem);
  887.         save_set_new(mem, false);
  888.         file_forget_save(mem);
  889.         combine_space(mem);    /* combine memory */
  890.         /* This is the outermost save, which might also */
  891.         /* need to combine global VM. */
  892.         mem = save->space_global;
  893.         if (mem != save->space_local && mem->saved != 0) {
  894.         forget_changes(mem);
  895.         save_set_new(mem, false);
  896.         file_forget_save(mem);
  897.         combine_space(mem);
  898.         }
  899.         alloc_set_not_in_save(dmem);
  900.         break;        /* must be outermost */
  901.     }
  902.     }
  903.     while (sprev != save);
  904. }
  905. /* Combine the chunks of the next outer level with those of the current one, */
  906. /* and free the bookkeeping structures. */
  907. private void
  908. combine_space(gs_ref_memory_t * mem)
  909. {
  910.     alloc_save_t *saved = mem->saved;
  911.     gs_ref_memory_t *omem = &saved->state;
  912.     chunk_t *cp;
  913.     chunk_t *csucc;
  914.  
  915.     alloc_close_chunk(mem);
  916.     for (cp = mem->cfirst; cp != 0; cp = csucc) {
  917.     csucc = cp->cnext;    /* save before relinking */
  918.     if (cp->outer == 0)
  919.         alloc_link_chunk(cp, omem);
  920.     else {
  921.         chunk_t *outer = cp->outer;
  922.  
  923.         outer->inner_count--;
  924.         if (mem->pcc == cp)
  925.         mem->pcc = outer;
  926.         if (mem->cfreed.cp == cp)
  927.         mem->cfreed.cp = outer;
  928.         /* "Free" the header of the inner chunk, */
  929.         /* and any immediately preceding gap left by */
  930.         /* the GC having compacted the outer chunk. */
  931.         {
  932.         obj_header_t *hp = (obj_header_t *) outer->cbot;
  933.  
  934.         hp->o_alone = 0;
  935.         hp->o_size = (char *)(cp->chead + 1)
  936.             - (char *)(hp + 1);
  937.         hp->o_type = &st_bytes;
  938.         /* The following call is probably not safe. */
  939. #if 0                /* **************** */
  940.         gs_free_object((gs_memory_t *) mem,
  941.                    hp + 1, "combine_space(header)");
  942. #endif /* **************** */
  943.         }
  944.         /* Update the outer chunk's allocation pointers. */
  945.         outer->cbot = cp->cbot;
  946.         outer->rcur = cp->rcur;
  947.         outer->rtop = cp->rtop;
  948.         outer->ctop = cp->ctop;
  949.         outer->has_refs |= cp->has_refs;
  950.         gs_free_object(mem->parent, cp,
  951.                "combine_space(inner)");
  952.     }
  953.     }
  954.     /* Update relevant parts of allocator state. */
  955.     mem->cfirst = omem->cfirst;
  956.     mem->clast = omem->clast;
  957.     mem->allocated += omem->allocated;
  958.     mem->gc_allocated += omem->allocated;
  959.     mem->lost.objects += omem->lost.objects;
  960.     mem->lost.refs += omem->lost.refs;
  961.     mem->lost.strings += omem->lost.strings;
  962.     mem->saved = omem->saved;
  963.     mem->previous_status = omem->previous_status;
  964.     {                /* Concatenate free lists. */
  965.     int i;
  966.  
  967.     for (i = 0; i < num_freelists; i++) {
  968.         obj_header_t *olist = omem->freelists[i];
  969.         obj_header_t *list = mem->freelists[i];
  970.  
  971.         if (olist == 0);
  972.         else if (list == 0)
  973.         mem->freelists[i] = olist;
  974.         else {
  975.         while (*(obj_header_t **) list != 0)
  976.             list = *(obj_header_t **) list;
  977.         *(obj_header_t **) list = olist;
  978.         }
  979.     }
  980.     if (omem->largest_free_size > mem->largest_free_size)
  981.         mem->largest_free_size = omem->largest_free_size;
  982.     }
  983.     gs_free_object((gs_memory_t *) mem, saved, "combine_space(saved)");
  984.     alloc_open_chunk(mem);
  985. }
  986. /* Free the changes chain for a level 0 .forgetsave, */
  987. /* resetting the l_new flag in the changed refs. */
  988. private void
  989. forget_changes(gs_ref_memory_t * mem)
  990. {
  991.     register alloc_change_t *chp = mem->changes;
  992.     alloc_change_t *next;
  993.  
  994.     for (; chp; chp = next) {
  995.     ref_packed *prp = chp->where;
  996.  
  997.     if_debug1('U', "[U]forgetting change 0x%lx\n", (ulong) chp);
  998.     if (!r_is_packed(prp))
  999.         r_clear_attrs((ref *) prp, l_new);
  1000.     next = chp->next;
  1001.     gs_free_object((gs_memory_t *) mem, chp, "forget_changes");
  1002.     }
  1003.     mem->changes = 0;
  1004. }
  1005. /* Update the streams list when forgetting a save. */
  1006. private void
  1007. file_forget_save(gs_ref_memory_t * mem)
  1008. {
  1009.     const alloc_save_t *save = mem->saved;
  1010.     stream *streams = mem->streams;
  1011.     stream *saved_streams = save->state.streams;
  1012.  
  1013.     if_debug4('u', "[u%d]file_forget_save 0x%lx + 0x%lx for 0x%lx\n",
  1014.           mem->space, (ulong) streams, (ulong) saved_streams,
  1015.           (ulong) save);
  1016.     if (streams == 0)
  1017.     mem->streams = saved_streams;
  1018.     else if (saved_streams != 0) {
  1019.     while (streams->next != 0)
  1020.         streams = streams->next;
  1021.     streams->next = saved_streams;
  1022.     saved_streams->prev = streams;
  1023.     }
  1024. }
  1025.  
  1026. /* ------ Internal routines ------ */
  1027.  
  1028. /* Set or reset the l_new attribute in every relevant slot. */
  1029. /* This includes every slot on the current change chain, */
  1030. /* and every (ref) slot allocated at this save level. */
  1031. /* Return the number of bytes of data scanned. */
  1032. private long
  1033. save_set_new(gs_ref_memory_t * mem, bool to_new)
  1034. {
  1035.     long scanned = 0;
  1036.  
  1037.     /* Handle the change chain. */
  1038.     save_set_new_changes(mem, to_new);
  1039.  
  1040.     /* Handle newly allocated ref objects. */
  1041.     SCAN_MEM_CHUNKS(mem, cp) {
  1042.     if (cp->has_refs) {
  1043.         bool has_refs = false;
  1044.  
  1045.         SCAN_CHUNK_OBJECTS(cp)
  1046.         DO_ALL
  1047.         if_debug3('U', "[U]set_new scan(0x%lx(%u), %d)\n",
  1048.               (ulong) pre, size, to_new);
  1049.         if (pre->o_type == &st_refs) {
  1050.         /* These are refs, scan them. */
  1051.         ref_packed *prp = (ref_packed *) (pre + 1);
  1052.         ref_packed *next = (ref_packed *) ((char *)prp + size);
  1053. #ifdef ALIGNMENT_ALIASING_BUG
  1054.         ref *rpref;
  1055. # define RP_REF(rp) (rpref = (ref *)rp, rpref)
  1056. #else
  1057. # define RP_REF(rp) ((ref *)rp)
  1058. #endif
  1059.  
  1060.         if_debug2('U', "[U]refs 0x%lx to 0x%lx\n",
  1061.               (ulong) prp, (ulong) next);
  1062.         has_refs = true;
  1063.         scanned += size;
  1064.         /* We know that every block of refs ends with */
  1065.         /* a full-size ref, so we only need the end check */
  1066.         /* when we encounter one of those. */
  1067.         if (to_new)
  1068.             while (1) {
  1069.             if (r_is_packed(prp))
  1070.                 prp++;
  1071.             else {
  1072.                 RP_REF(prp)->tas.type_attrs |= l_new;
  1073.                 prp += packed_per_ref;
  1074.                 if (prp >= next)
  1075.                 break;
  1076.             }
  1077.         } else
  1078.             while (1) {
  1079.             if (r_is_packed(prp))
  1080.                 prp++;
  1081.             else {
  1082.                 RP_REF(prp)->tas.type_attrs &= ~l_new;
  1083.                 prp += packed_per_ref;
  1084.                 if (prp >= next)
  1085.                 break;
  1086.             }
  1087.             }
  1088. #undef RP_REF
  1089.         } else
  1090.         scanned += sizeof(obj_header_t);
  1091.         END_OBJECTS_SCAN
  1092.         cp->has_refs = has_refs;
  1093.     }
  1094.     }
  1095.     END_CHUNKS_SCAN
  1096.     if_debug2('u', "[u]set_new (%s) scanned %ld\n",
  1097.           (to_new ? "restore" : "save"), scanned);
  1098.     return scanned;
  1099. }
  1100.  
  1101. /* Set or reset the l_new attribute on the changes chain. */
  1102. private void
  1103. save_set_new_changes(gs_ref_memory_t * mem, bool to_new)
  1104. {
  1105.     register alloc_change_t *chp = mem->changes;
  1106.     register uint new = (to_new ? l_new : 0);
  1107.  
  1108.     for (; chp; chp = chp->next) {
  1109.     ref_packed *prp = chp->where;
  1110.  
  1111.     if_debug3('U', "[U]set_new 0x%lx: (0x%lx, %d)\n",
  1112.           (ulong)chp, (ulong)prp, new);
  1113.     if (!r_is_packed(prp)) {
  1114.         ref *const rp = (ref *) prp;
  1115.  
  1116.         rp->tas.type_attrs =
  1117.         (rp->tas.type_attrs & ~l_new) + new;
  1118.     }
  1119.     }
  1120. }
  1121.